package com.qf.face.service.impl;

import com.baidu.aip.face.AipFace;
import com.qf.base.utils.Base64Util;
import com.qf.face.dao.RequestLogDao;
import com.qf.face.model.RequestLog;
import com.qf.face.service.FaceService;
import com.qf.face.utils.BaiduUtil;
import com.qf.face.utils.FaceUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.image.BufferedImage;

/**
 * @author 30909
 */
@Service
public class FaceServiceImpl implements FaceService {


    @Resource
    private AipFace aipFace;
    @Resource
    private RequestLogDao requestLogDao;

    @Override
    public boolean addFace(Long userId, String image, Integer serviceId) {
        RequestLog requestLog = new RequestLog();
        requestLog.setActionId(1);
        requestLog.setServiceId(serviceId);
        requestLogDao.insertSelective(requestLog);
        BaiduUtil.addFace(aipFace, image, userId);

        return true;
    }

    @Override
    public boolean editFace(Long userId, String image, Integer serviceId) {
        RequestLog requestLog = new RequestLog();
        requestLog.setActionId(2);
        requestLog.setServiceId(serviceId);
        requestLogDao.insertSelective(requestLog);
        //判读有没有脸
        //image 是 base64 ,怎么转化成bufferedImages
        BufferedImage bufferedImage = Base64Util.base64ToImage(image);
        bufferedImage = FaceUtil.haveFace(bufferedImage);
        if (bufferedImage == null) {
            //图片中没有脸
            return false;
        }
        BaiduUtil.updateFace(aipFace, image, userId);
        return true;
    }

    @Override
    public boolean removeFace(Long userId, Integer serviceId) {

        RequestLog requestLog = new RequestLog();
        requestLog.setActionId(3);
        requestLog.setServiceId(serviceId);
        requestLogDao.insertSelective(requestLog);
        BaiduUtil.delFace(aipFace, userId);
        return false;
    }

    @Override
    public Long search(String image, Integer serviceId) {

        RequestLog requestLog = new RequestLog();
        requestLog.setActionId(4);
        requestLog.setServiceId(serviceId);
        requestLogDao.insertSelective(requestLog);
        //判读有没有脸
        //image 是 base64 ,怎么转化成bufferedImages
        BufferedImage bufferedImage = Base64Util.base64ToImage(image);
        bufferedImage = FaceUtil.haveFace(bufferedImage);
        if (bufferedImage == null) {
            //图片中没有脸
            return null;
        }
        /**
         * 这里要改
         */
        return BaiduUtil.search(aipFace, Base64Util.image2Base64(bufferedImage));
//        return BaiduUtil.search(aipFace, image);

    }
}
